﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace ZR.Infrastructure.Resolver;

public class PropertyFilterContractResolver : CamelCasePropertyNamesContractResolver
{
    private readonly HashSet<string> _includedPaths;
    private readonly HashSet<string> _excludedPaths;
    
    public PropertyFilterContractResolver(IEnumerable<string> includedPaths, IEnumerable<string> excludedPaths)
    {
        _includedPaths = includedPaths.ToHashSet();
        _excludedPaths = excludedPaths.ToHashSet();
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);
        
        properties = properties.Where(p => IsIncluded(p) && !IsExcluded(p)).ToList();

        return properties;
    }
    
    private bool IsIncluded(JsonProperty property)
    {
        if (_includedPaths == null || _includedPaths.Count == 0)
            return true;

        return _includedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
    }

    private bool IsExcluded(JsonProperty property)
    {
        if (_excludedPaths == null || _excludedPaths.Count == 0)
            return false;

        return _excludedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
    }
}